package com.adeoservices.gwt.dispatch.spring.server.security;

import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.AccessDeniedException;
import org.springframework.stereotype.Component;

@Component
public class DefaultPermissionVerifierRegistry implements PermissionVerifierRegistry {

	private Log logger = LogFactory.getLog(PermissionVerifierRegistry.class);
	
    private final Map<Class<? extends PermissionVerifier<?, ?>>, PermissionVerifier<?, ?>> verifiers;

    public DefaultPermissionVerifierRegistry() {
        verifiers = new java.util.HashMap<Class<? extends PermissionVerifier<?, ?>>, PermissionVerifier<?, ?>>( );
    }

	@Override
    public PermissionVerifier<?, ?> findPermissionVerifier( Class<? extends PermissionVerifier<?, ?>> permissionVerifierClass ) {
    	
    	if (!verifiers.containsKey(permissionVerifierClass))
    	{
    		try {
    			logger.info("Creating permission verifier instance for class : " + permissionVerifierClass);
				verifiers.put(permissionVerifierClass, permissionVerifierClass.newInstance());
			} catch (InstantiationException e) {
				logger.warn(e.getMessage(), e);
			} catch (IllegalAccessException e) {
				logger.warn(e.getMessage(), e);
			}
    	}
    	
        PermissionVerifier<?, ?> permissionVerifier = (PermissionVerifier<?, ?> ) verifiers.get( permissionVerifierClass );
        
        if (permissionVerifier == null)
        {
        	logger.warn("No permission verifier : " + permissionVerifierClass);
        	throw new AccessDeniedException("Access denied");
        }
        
        return permissionVerifier;
    }

}
